
import grpc
import time
import stream_pb2
import stream_pb2_grpc 


# 第1个接口 SayGreeting 
def say_greeting(stub):
    res = stub.SayGreeting(
        stream_pb2.GreetRequest(
            greet_word='Good Morning', 
            user=[stream_pb2.Person(name='Jack'), stream_pb2.Person(name="Smith") ]
            )
        )
    if res:
        print(res.response)
    return None

# 第2个接口 MultiGreeting 
def make_greeting(greet,name1,name2):
    return stream_pb2.GreetRequest(
            greet_word=greet, 
            user=[stream_pb2.Person(name=name1), stream_pb2.Person(name=name2) ]
        )

def generate_greetings():
    greetings = [
        make_greeting("Good morning","Storn","abcd"),
        make_greeting("How are you","Adfdsf","adfidd"),
        make_greeting('Are your fine', "Wang","Zhang" ),
    ]
    #! 也使用迭代器
    for greet in greetings:
        print(f"greet_word: {greet.greet_word} , users: {greet.user} ")
        yield greet

def multiple_greeting(stub):
    resp = stub.MultiGreeting(generate_greetings())
    print(resp)

def multiple_greeting_response(stub):
    responses  = stub.MultiGreetingResp(
        stream_pb2.GreetRequest(
            greet_word='Good Morning', 
            user=[stream_pb2.Person(name='Zhang'), stream_pb2.Person(name="Smith") ]
            )
        )
    for res in responses:
        print(res.response)
    return None        

def run():
    with grpc.insecure_channel('localhost:8888') as channel:
        stub = stream_pb2_grpc.GreetingStub(channel)
        print("-------------- SayGreeting --------------")
        say_greeting(stub)
        # time.sleep(3)
        # print("\n-------------- MultiGreeting --------------")
        # multiple_greeting(stub)   
        
        # time.sleep(3)     
        print("\n-------------- MultiGreetingResponse --------------")
        # multiple_greeting_response(stub)       


if __name__=="__main__":
    run()
